package net.chrone.quickpayapi.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.chrone.quickpayapi.model.Merchant;
import net.chrone.quickpayapi.model.PlatOrgInf;
import net.chrone.quickpayapi.model.PmsBankInf;
import net.chrone.quickpayapi.service.MerchantService;
import net.chrone.quickpayapi.service.PlatOrgInfService;
import net.chrone.quickpayapi.service.PmsBankInfService;
import net.chrone.quickpayapi.util.Constant;
import net.chrone.quickpayapi.util.RegexUtil;
import net.chrone.quickpayapi.util.SignatureUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping("/v1.0/merchant")
public class MerchantController {
	
	private  final Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private PlatOrgInfService platOrgInfService;
	@Autowired
	private PmsBankInfService pmsBankInfService;
	@Autowired
	private MerchantService merchantService;

	@Transactional(rollbackFor=Exception.class)
	@RequestMapping(value="/regist",method=RequestMethod.POST,produces=MediaType.APPLICATION_JSON_VALUE)
	public void regist(@RequestBody Merchant reqParams,HttpServletResponse response)throws Exception{
		logger.debug(reqParams);
		Map<String,String> respMap = new HashMap<String, String>();
		if(StringUtils.isEmpty(reqParams.getOrgId())){
			logger.error("机构号不能为空");
			respMap.put("respCode","401");
			response(respMap,response);
			return;
		}
		PlatOrgInf platOrgInf = platOrgInfService.findById(reqParams.getOrgId());
		if(platOrgInf==null){
			logger.error("找不到机构信息,orgId:"+reqParams.getOrgId());
			respMap.put("respCode","402");
			response(respMap,response);
			return;
		}
		boolean flag = SignatureUtil.verify(reqParams.getSignature(), reqParams,platOrgInf.getPublicKey());
		if(!flag){
			logger.error("验签失败");
			respMap.put("respCode","403");
			response(respMap,response);
			return;
		}
		if(StringUtils.isEmpty(reqParams.getAccount())||!RegexUtil.validMobile(reqParams.getAccount())){
			logger.error("account格式错,account:"+reqParams.getAccount());
			respMap.put("respCode","404");
			response(respMap,response);
			return;
		}
		if(StringUtils.isEmpty(reqParams.getCardNo())||!RegexUtil.validCard(reqParams.getCardNo())){
			logger.error("卡号格式错,cardNo:"+reqParams.getCardNo());
			respMap.put("respCode","405");
			response(respMap,response);
			return;
		}
		if((StringUtils.isEmpty(reqParams.getCertType())||"00".equals(reqParams.getCertType()))&&!RegexUtil.validIDCard(reqParams.getCertNo())){
			logger.error("身份证格式错");
			respMap.put("respCode","406");
			response(respMap,response);
			return;
		}
		PmsBankInf pmsBankInf = pmsBankInfService.find(reqParams.getPmsBankNo());
		if(null==pmsBankInf){
			logger.error("开户行不存在,pms_bank_no:"+reqParams.getPmsBankNo());
			respMap.put("respCode","407");
			response(respMap,response);
			return;
		}else{
			reqParams.setCityCd(pmsBankInf.getCityCd());
		}
		if(StringUtils.isNotEmpty(reqParams.getMobile())&&!RegexUtil.validMobile(reqParams.getMobile())){
			logger.error("结算卡绑定手机号码格式错,mobile:"+reqParams.getMobile());
			respMap.put("respCode","408");
			response(respMap,response);
			return;
		}
		if(StringUtils.isEmpty(reqParams.getMchntName())){
			logger.error("商户名称不能为空");
			respMap.put("respCode","409");
			response(respMap,response);
			return;
		}
		if(StringUtils.isEmpty(reqParams.getRealName())){
			logger.error("户名不能为空");
			respMap.put("respCode","410");
			response(respMap,response);
			return;
		}
		//如果商户已经存在并且状态
		Merchant mchnt = merchantService.find(reqParams.getOrgId(), reqParams.getAccount());
		if(null!=mchnt&&mchnt.getAccountSt()==Constant.MCHNT_ST_AUDIT_PASS){
			logger.error("账户已存在,account:"+reqParams.getAccount());
			respMap.put("respCode","417");
			response(respMap,response);
			return;
		}
		if(mchnt==null){
			logger.debug("=================插入数据库=======================");
			mchnt = merchantService.regist(reqParams);//如果没有就插入
		}else{//如果有就修改状态
			logger.debug("=================更新数据库信息=======================");
			reqParams.setMchntId(mchnt.getMchntId());
			reqParams.setAccountSt(Constant.MCHNT_ST_AUDIT_PASS);
			int i = merchantService.update(reqParams);
			if(i==1){
				logger.debug("更新成功");
				mchnt = merchantService.find(reqParams.getOrgId(), reqParams.getAccount());//更新完毕之后重新再查一次
			}
		}
//		if(Constant.MCHNT_ST_UNREGIST==mchnt.getAccountSt()&&!merchantService.kubeiRegist(mchnt)){
//			respMap.put("respCode","601");//库贝注册失败
//			response(respMap,response);
//			return;
//		}
//		if(Constant.MCHNT_ST_NONE_KEY==mchnt.getAccountSt()&&!merchantService.downloadPrivateKey(mchnt)){
//			respMap.put("respCode","602");//库贝下载密钥失败
//			response(respMap,response);
//			return;
//		}
//		if(Constant.MCHNT_ST_UNVALID_CARD==mchnt.getAccountSt()&&!merchantService.validCard(mchnt)){
//			respMap.put("respCode","603");//库贝验卡失败
//			response(respMap,response);
//			return;
//		}
		if(mchnt==null){
			respMap.put("respCode","100");//注册失败,系统异常
		}else{
			respMap.put("respCode","200");//库贝验卡失败
		}
		//说明成功注册了
		response(respMap,response);
	}
	
	
	/**
	 * 商户查询
	 * @param merchant
	 * @param response
	 */
	@RequestMapping(value="/query",produces=MediaType.APPLICATION_JSON_VALUE)
	public void query(@RequestBody Merchant merchant,HttpServletResponse response){
		logger.debug(merchant);
		Map<String,String> respMap = new HashMap<String, String>();
		if(StringUtils.isEmpty(merchant.getOrgId())){
			logger.error("机构号不能为空");
			respMap.put("respCode","401");
			response(respMap,response);
			return;
		}
		PlatOrgInf platOrgInf = platOrgInfService.findById(merchant.getOrgId());
		if(platOrgInf==null){
			logger.error("找不到机构信息,orgId:"+merchant.getOrgId());
			respMap.put("respCode","402");
			response(respMap,response);
			return;
		}
		boolean flag = SignatureUtil.verify(merchant.getSignature(), merchant,platOrgInf.getPublicKey());
		if(!flag){
			logger.error("验签失败");
			respMap.put("respCode","403");
			response(respMap,response);
			return;
		}
		if(StringUtils.isEmpty(merchant.getAccount())||!RegexUtil.validMobile(merchant.getAccount())){
			logger.error("account格式错,account:"+merchant.getAccount());
			respMap.put("respCode","404");
			response(respMap,response);
			return;
		}
		Merchant mchnt = merchantService.find(merchant.getOrgId(), merchant.getAccount());
		if(mchnt==null){
			logger.error("account不存在,account:"+merchant.getAccount());
			respMap.put("respCode","411");
			response(respMap,response);
			return;
		}else{
			respMap.put("respCode","200");
			respMap.put("accountSt", mchnt.getAccountSt()+"");
			response(respMap,response);
			return;
		}
	}
	
	/**
	 * 费率修改
	 * @param merchant
	 * @param response
	 */
	@RequestMapping(value="/feeRateSync",produces=MediaType.APPLICATION_JSON_VALUE)
	public void feeRateSync(@RequestBody Merchant merchant,HttpServletResponse response){
		logger.debug(merchant);
		Map<String,String> respMap = new HashMap<String, String>();
//		if(StringUtils.isEmpty(merchant.getOrgId())){
//			logger.error("机构号不能为空");
//			respMap.put("respCode","401");
//			response(respMap,response);
//			return;
//		}
//		PlatOrgInf platOrgInf = platOrgInfService.findById(merchant.getOrgId());
//		if(platOrgInf==null){
//			logger.error("找不到机构信息,orgId:"+merchant.getOrgId());
//			respMap.put("respCode","402");
//			response(respMap,response);
//			return;
//		}
//		boolean flag = SignatureUtil.verify(merchant.getSignature(), merchant,platOrgInf.getPublicKey());
//		if(!flag){
//			logger.error("验签失败");
//			respMap.put("respCode","403");
//			response(respMap,response);
//			return;
//		}
//		if(StringUtils.isEmpty(merchant.getAccount())||!RegexUtil.validMobile(merchant.getAccount())){
//			logger.error("account格式错,account:"+merchant.getAccount());
//			respMap.put("respCode","404");
//			response(respMap,response);
//			return;
//		}
		Merchant mchnt = merchantService.find(merchant.getOrgId(), merchant.getAccount());
//		if(mchnt==null){
//			logger.error("account不存在,account:"+merchant.getAccount());
//			respMap.put("respCode","411");
//			response(respMap,response);
//			return;
//		}
//		KubeiBean respBean = KubeiApi.feeRateSync(mchnt,merchant.getFeeRate()+"");
//		if(null!=respBean&&KubeiApi.SUCCESS_CODE.equals(respBean.getRespCode())){
			mchnt.setFeeRate(merchant.getFeeRate());
			merchantService.update(merchant);//修改费率
			respMap.put("respCode","200");
			response(respMap,response);
			return;
//		}else{
//			respMap.put("respCode","412");
//			response(respMap,response);
//			return;
//		}
	}
	
	private void response(Map<String, String> respMap,HttpServletResponse response) {
		respMap.put("respMsg", Constant.getErrorCodeMap().get(respMap.get("respCode")));
		respMap.put("signature", SignatureUtil.signResp(respMap));
		String json = JSON.toJSONString(respMap);
		try {
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(json);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
